<template>
	<view style="overflow: hidden;min-height: 100%; background-color: #f8f8f8;">
		<!-- 导航栏 -->
		<order-header class="custom-navbar" title="订单详情" 
			:status="statusInfo.status" 
			:image="statusInfo.image"
			:bt-text="statusInfo.btText" 
			@btClick="statucClick" 
			:expire="expire" 
			@back="back" 
			:isOffline="statusInfo.state == 0&&info.paymentMethod==3" 
			:orderOffline="statusInfo.state == 0&&info.paymentMethod==3"
			>
		</order-header>
		<!-- 导航栏占位盒子 -->
		<!-- #ifdef APP-PLUS -->
		<view  :style="{height:  '240rpx',marginTop:statusBarHeight+'rpx'}"></view>
		<!-- #endif -->
		<!-- #ifndef APP-PLUS -->
		<view :style="{height:  '240rpx'}"></view>
		<!-- #endif -->
		<view class="u-p-l-30 u-p-t-30 u-p-r-30" >
			<view v-if="info.state<4" class="u-p-l-35 u-p-r-35 u-p-t-28 u-p-b-28 u-font-28 u-bg-white u-theme-main" >
				<view>{{orderStatusTips(info.state,info.timeExpire)}}</view>
			</view>
			<!-- 付款单 -->
			<view class="u-m-t-20  box-padding box-color bottom-speac" v-if="info.state!==5" @click="goCreatePayFn()">
				<view class="u-flex u-row-between" >
					<view class="u-flex u-col-center">
						<image src="/static/order/zhifudan.png" mode="" style="width: 74rpx;height: 74rpx;"></image>
						<text class="u-font-32 u-m-l-30 u-font-bold" >收款单</text>
					</view>
					<view class="u-flex ">
						<view class="u-flex u-font-28">
							<view class="grey-color" v-if="info.tradePaymentId==null&&info.tradePaymentNo == null">发起收款单</view>
							<!-- <view class="grey-color"  v-else>{{payMethodStatus[info.paymentMethod]}}</view>
							<text class="u-m-l-10 u-m-r-10" style="color: #999;">|</text> -->
							<view v-else>
								<view class="u-text-right u-font-28 u-theme-main">{{paymentStatus[info.paymentStatus]}}</view>
								<view class=" u-font-22 ">{{info.tradePaymentNo}}</view>
							</view>
						</view>
						<view>
							<fui-icon name="arrowright"  style="color: #999999;" size="38"></fui-icon>
						</view>
					</view>
				</view>
				<!-- 信用额度进度条 -->
				<!-- :style="{position: 'fixed',top:(statusBarHeight+222)+'rpx',width:'100%',zIndex: 999}" -->
				<view class="u-m-t-20"  v-if="info.settlementMethod === 1">
					<view style=" box-sizing: border-box; width: 100%;background-color: #FFFFFF;">
						<view style="" >
							<process-used @sendAdequate="isAdequateFn" :sellerId="info.sellerShopId" :buyerId="info.buyerShopId" :totalPrice="info.actualAmount" :noTips="true"></process-used>
						</view>
					</view>
				</view>
			</view>
			<!-- 地址 -->
			<ak-address class="u-m-t-20 u-m-b-20" :address="address"></ak-address>
			<!-- 订单信息 -->
			<ak-order-goods :info="info" :role="'sale'" @openPop="openHistory"></ak-order-goods>
			<!-- 支付信息 -->
			<ak-order-info :info="info"></ak-order-info>
			<!-- 物流信息 -->
			<ak-order-logistics v-if="info.deliveryNote" :info="info.deliveryNote"></ak-order-logistics>
			
			<view class="box-padding-col u-flex u-m-t-20" style="background-color: #FFFFFF;height: 114rpx; margin-bottom: 40rpx;line-height: 114rpx;">
				<image src="/static/order/beizhu.png" style="width: 40rpx;height:36rpx;" mode=""></image>
				<text class="u-m-l-14 u-m-r-14">备注</text> 
				<fui-textarea autoHeight :padding="['10rpx 28rpx']"	v-model="info.sellerRemarks" @blur="saveRemarks" placeholder="请输入备注"></fui-textarea>
			</view>
		</view>
		
		
		<!-- 占位盒子 -->
		<view style="height: 160rpx;" v-if="statusInfo.state==0||statusInfo.state==2||statusInfo.state==3"></view>
		<!-- 底部固定客服 -->
		<view class="footer" v-if="statusInfo.state==0||statusInfo.state==1||statusInfo.state==3">
			<fui-button text="取消订单" class="u-m-r-20" v-if="statusInfo.state == 0" @click="cancelOrderFn" height="80rpx" width="200rpx" radius="45rpx" size="32" background="#F8F8F8" color="#999"></fui-button>
			<fui-button text="确认订单" class="u-m-r-20" v-if="statusInfo.state == 0&&info.settlementMethod!=0" 
			 height="80rpx" width="200rpx" radius="45rpx" size="32" background="#FFECBF" color="#FFBB1A"
			 @click="modalContent=isAdequate?'先货后款订单，确认后订单将跳过付款环节，是否确认订单':'该采购商信用额度已用完，暂无法确认该订单。请发起收款单让对方尽快支付欠款，释放额度后再来确认本订单';modalType='queren';modalShow = true"
			 ></fui-button>
			<fui-button text="物流发货"  class="u-m-r-20" v-if="statusInfo.state == 1" @click="goLogisticsPage"
			height="80rpx" width="200rpx" radius="45rpx" size="32" background="#FFECBF" color="#FFBB1A"></fui-button>
		</view>
		<!-- 确认取消弹窗 -->
		<u-modal v-model="modalShow" :content="modalContent" :show-confirm-button="isAdequate" :show-cancel-button="true" @confirm="handleSubmit"></u-modal>
		<!-- 录入单号 -->
		<u-popup v-model="logisticsShow" mode="bottom">
			<view class="box-padding">
				<u-field v-model="logisticsNo" required :field-style="{marginLeft: '20rpx'}" label="物流单号" placeholder="请输入物流单号" placeholder-style="color: #999999;" />
				<u-field v-model="logisticsCompany" required :field-style="{marginLeft: '20rpx'}" label="物流公司" placeholder="输入单号自动识别" placeholder-style="color: #999999;" />
				<view class="u-flex u-row-center" style="height: 80rpx;">
					<text class="u-font-32 theme-color" @click="handleLogistics">确认</text>
				</view>
			</view>
		</u-popup>
		<!-- 拒绝弹窗 -->
		<u-popup v-model="cancelledShow" mode="bottom">
			<view class="box-padding">
				<textarea v-model="cancelledReason" placeholder="请输入取消原因" style="height: 130rpx;padding-bottom: 20rpx;width: 100%;" />
				<u-button shape="circle" :hair-line="false" hover-class="none" :custom-style="getBtStyle('default')" @click="cancel">确认</u-button>
			</view>
		</u-popup>
		<view v-html="alipayDom"></view>
		<!-- 无法取消支付单弹窗 -->
		<u-modal v-model="notCancelShow" :content="'当前订单已被线下支付，只能由买家取消支付单后才能取消订单，如需取消请联系买家处理~'" 
		:show-cancel-button="false">
		</u-modal>
	</view>
</template>

<script>
	let systemInfo = uni.getSystemInfoSync();
	import OrderHeader from '@/components/order-header.vue'
	import AkAddress from '@/components/ak-order/address.vue'
	import AkOrderGoods from '@/components/ak-order/goods.vue'
	import AkOrderInfo from '@/components/ak-order/info.vue'
	import AkOrderLogistics from '@/components/ak-order/logistics.vue';
	import { useUserStore } from '@/store/user.js';
	import { useShopStore } from '@/store/shop.js';
	import { orderStore } from '@/store/order.js';
	import { mapState } from 'pinia';
	import utils from '@/components/firstui/fui-utils';
	import ProcessUsed from '@/components/process-used/index.vue'
	export default {
		components: {
			OrderHeader,
			AkAddress,
			AkOrderGoods,
			AkOrderInfo,
			AkOrderLogistics,
			ProcessUsed
		},
		data() {
			return {
				id: null,
				alipayDom: '',
				modalShow: false,
				modalContent: '是否确认取消订单',
				modalType: 'shoukuan',
				logisticsShow: false,
				logisticsNo: '',
				logisticsCompany: '',
				info: {},
				address: {},
				invoice: {},
				state: 0,
				statusInfo: {},
				boxHeight: 0,
				payTypeShow: false,
				paymentMethod: null,
				expire: '',
				isGoPay:false,
				loading:false,
				payList:[],
				offlineSet:{},
				tradePaymentId:'',
				paymentStatus:['待付款','待到账','已完成','部分完成','支付失败','已关闭','退款中','已退款',],
				tradePaymentNo:'',
				statusBarHeight: systemInfo.statusBarHeight,
				dataList:[],
				joinedActivity:'',
				payMethodStatus:['微信支付','支付宝支付','银联支付','线下支付','线下支付'],
				isAdequate:true,
				notCancelShow:false,
				cancelledShow: false,
				cancelledReason: '',
			}
		},
		computed:{
			...mapState(useUserStore,['isSale','isSendOut','isCollection']),
			...mapState(orderStore,['orderStatus']),
			...mapState(useShopStore, {
				storeShop: 'shop',
			})	
		},
		async onLoad(options) {
			this.id = options.id;
			this.joinedActivity = options.activityId
		},
		onShow() {
			if(this.isGoPay){
				this.$mRouter.redirectTo({
					route: '/pages/sale/payorder/payresult?id=' + this.id
				})
			}
			this.getOrderDetail();
		},
		methods: {
			// 改变状态
			async handleSubmit() {
				if (this.modalType == 'shoukuan') {
					if(!this.isCollection){
						return this.$u.toast('当前账号没有确认收款的权限')
					}
					const res = await this.$http.put('api/Trade/PaymentReceived?id=' + this.id)
					this.$u.toast('收款成功', 1000, 'success')
				} else if (this.modalType == 'quxiao') {
					if(!this.isSale){
						return this.$u.toast('当前账号没有取消订单的权限')
					}
					const res = await this.$http.put('api/Trade/PaymentReceived?id=' + this.id)
					this.$u.toast('取消成功', 1000, 'success')
				} else if (this.modalType == 'fahuo') {
					if(!this.isSendOut){
						return this.$u.toast('当前账号没有自行发货的权限')
					}
					const data = {
						id: this.id,
						sendUserId: this.$store.state.user.user.id
					}
					const res = await this.$http.put('api/Trade/SelfDelivery', data)
					this.$u.toast('发货成功', 1000, 'success')
				}else if(this.modalType == 'queren'){
					if(!this.isAdequate){
						return this.$u.toast('该采购商信用额度已用完，暂无法确认该订单。请发起收款单让对方尽快支付欠款，释放额度后再来确认本订单')
					};
					if(!this.isCollection){
						return this.$u.toast('当前账号没有确认订单的权限')
					}
					const res = await this.$http.put('api/Trade/PaymentReceived?id=' + this.id)
					this.$u.toast('确认订单成功', 1000, 'success')
				}
				this.$mHelper.delayedJump('/pages/sale/order/index', 'redirectTo')
			},
			cancelOrderFn(){
				if(this.info.tradePaymentId==null){
					this.cancelledShow = true;
				}else if(this.info.paymentMethod === 3&&this.info.paymentStatus === 1){
					this.notCancelShow = true;
				}else{
					this.$u.toast('订单已被收款单关联，请在收款单中解除关联后再进行此操作~')
				}
			},
			async saveRemarks() {
				console.log(this.info.sellerRemarks)
				await this.$http.put('api/Trade/WriteSellerRemarks', { id: this.id, sellerRemarks: this.info.sellerRemarks })
			},
			// 物流发货
			async handleLogistics() {
				if(!this.isSendOut){
					return this.$u.toast('当前账号没有物流发货的权限')
				}
				if (!this.logisticsCompany) {
					return this.$u.toast('请输入物流公司')
				}
				if (!this.logisticsNo) {
					return this.$u.toast('请输入物流单号')
				}
				const data = {
					id: this.id,
					logisticsNo: this.logisticsNo,
					logisticsCompany: this.logisticsCompany
				}
				const res = await this.$http.put('api/Trade/LogisticsDelivery', data)
				this.logisticsShow = false
				this.$u.toast('发货成功', 1000, 'success')
				this.$mHelper.delayedJump('/pages/sale/order/index', 'redirectTo')
			},
			isAdequateFn(val){
				console.log(val);
				this.isAdequate = val.isAdequate;
			},
			// 前往物流发货页面
			goLogisticsPage(){
				if(!this.isSendOut){
					return this.$u.toast('当前账号没有物流发货的权限')
				}
				this.$mRouter.push({
					route: '/pages/sale/order/delivery?buyerName='+this.info.buyerShopName+'&tradeNo='+this.info.tradeNo+'&orderId='+this.info.id
				})
			},
			// 取消
			async cancel() {
				if(!this.isSale){
					return this.$u.toast('当前账号没有取消订单的权限')
				}
				if (!this.cancelledReason) return this.$u.toast('请输入取消原因')
				const res = await this.$http.put('api/Trade/SellerCancellationTrade', { id: this.id, cancelledReason: this.cancelledReason })
				this.cancelledShow = false
				this.cancelledReason = ''
				this.$u.toast('取消成功', 1000, 'success')
				this.$mHelper.delayedJump('/pages/sale/order/index', 'redirectTo')
			},
			// 自动操作提示
			orderStatusTips(type, timeExpire) {
			  let nowTime = new Date();
			  let endTime = new Date(timeExpire);
			  var leftTime = endTime.getTime() - nowTime.getTime();
			  let isExpire = leftTime < 0 ? false : true;
			  let text = '';
			  let initTime = this.$u.timeFormat(timeExpire, 'yyyy年mm月dd日 hh时MM分');
			  switch (type) {
				case 0:
				  if (this.info.settlementMethod === 1) {
					text = '待确认，先货后款：若本订单未在【' + initTime+ '】前被确认，系统将自动取消本订单';
				  } else {
					text = '待确认，先款后货：若采购商未在【' +initTime+ '】前发起付款，系统将自动取消本订单';
				  }
				  return isExpire ? text : '系统将自动取消本订单';
				  break;
				case 1:
				  return '若本订单未在【' +initTime+ '】前发货，提醒发货员发货';
				  break;
				case 2:
				  text = '系统将在【' +initTime+ '】后自动收货';
				  return isExpire ? text : '系统将自动收货';
				  break;
				case 3:
				  text = '系统将在【' +initTime+ '】后自动完成订单';
				  return isExpire ? text : '系统将自动完成订单';
				  break;
				default: return '';
			  }
			},
			// 获取订单详情
			async getOrderDetail() { 
				const res = await this.$http.get('api/Trade/GetSaleTradeDetail', {
					params: {
						id: this.id
					}
				})
				this.info = res;
				this.address = res.deliveryAddress
				this.invoice = res.shopInvoiceConfig
				this.statusInfo = this.orderStatus.find(item => {
					return item.state == res.state // 待付款
				})
				this.tradePaymentId = res.tradePaymentId;
				this.tradePaymentNo = res.tradePaymentNo;
			},
			statucClick() {
				// 3 评价
				if (this.statusInfo.state == 3) {
					this.$mRouter.push({
						route: '/pages/sale/order/pingjia?id=' + this.id
					})
				}
			},
			// 查看支付单详情
			goPayDetailsFn(){
				if(!this.isCollection){
					return this.$u.toast('当前账号没有查看收款单的权限，请联系管理员处理~');
				}
				this.$mRouter.push({
					route: '/pages/sale/payorder/details?id='+this.tradePaymentId+'&routeFrom=order&orderId='+this.info.id
				})
			},
			back() {
				let pages = getCurrentPages(); // 当前页面
				let beforePage = pages[pages.length - 2]; // 上一页
				console.log(beforePage); 
				if(beforePage){
					if(beforePage.route === 'pages/public/xiaoxi/messageDeatails'||beforePage.route === 'pages/index/huodong'||beforePage.route === 'pages/purchase/zhanghu/tradeDetails'){
						uni.navigateBack();
					}else{
						this.$mRouter.redirectTo({
							route: '/pages/sale/order/index'
						})
					}
				}else{
					this.$mRouter.redirectTo({
						route: '/pages/sale/order/index'
					})
				}
			},
			goCreatePayFn(){
				if (!this.isCollection) {
					return this.$u.toast('您没有收款权限，请联系有付款权限的同事付款')
				}
				if(this.info.tradePaymentId==null){
					this.$mRouter.push({
						route: '/pages/sale/payorder/createPayOrder?shop='+this.info.buyerShopId+'&routeFrom=order&orderId='+this.info.id
					})
				
				}else{
					this.$mRouter.push({
						route: '/pages/sale/payorder/details?id='+this.tradePaymentId+'&routeFrom=order&orderId='+this.info.id
					})
				}
			}
			
		}
	}
</script>

<style lang="scss" scoped>
	.yx-bt {
		width: 200rpx;
		height: 80rpx;
		border: 2rpx solid $uni-text-color;
		border-radius: 40px;
		text-align: center;
		line-height: 80rpx;
		font-size: 28rpx;
	}
	.paryorder-mark{
		width: 5rpx;
		height: 16rpx;
		background: #FF551A;
		border-radius: 3rpx;
		margin-right: 14rpx;
	}
	.promition-item{
		box-sizing: border-box;
		padding: 28rpx 0rpx;
		background-color: #F8F8F8;
		border-bottom: 1px solid #eaeaea;
	}
	.footer {
		height: 140rpx;
		width: 100%;
		position: fixed;
		bottom: 0;
		background-color: #FFFFFF;
		display: flex;
		justify-content: flex-end;
		align-items: center;
		padding: 30rpx 35rpx;
		z-index: 9;
		border-top: 1rpx solid #EEEEEE;
	}
</style>
